#!/bin/bash
# 多功能Linux运维工具脚本
# 版本: 2.0
# 作者: SysAdmin Team
# 功能: 基于风险级别的系统监控与管理

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
ORANGE='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # 无颜色

# 风险级别定义
RISK_NORMAL="${GREEN}正常${NC}"
RISK_LOW="${YELLOW}低风险${NC}"
RISK_MEDIUM="${ORANGE}中风险${NC}"
RISK_HIGH="${RED}高风险${NC}"

# 检查是否以root用户运行
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}错误: 此脚本需要以root权限运行。请使用sudo或切换到root用户。${NC}" >&2
        exit 1
    fi
}

# 评估CPU风险等级
evaluate_cpu_risk() {
    local cpu_usage=$1
    if (( $(echo "$cpu_usage < 70" | bc -l) )); then
        echo "$RISK_NORMAL"
    elif (( $(echo "$cpu_usage >= 70 && $cpu_usage < 85" | bc -l) )); then
        echo "$RISK_LOW"
    elif (( $(echo "$cpu_usage >= 85 && $cpu_usage < 95" | bc -l) )); then
        echo "$RISK_MEDIUM"
    else
        echo "$RISK_HIGH"
    fi
}

# 评估内存风险等级
evaluate_memory_risk() {
    local memory_usage=$1
    if (( $(echo "$memory_usage < 70" | bc -l) )); then
        echo "$RISK_NORMAL"
    elif (( $(echo "$memory_usage >= 70 && $memory_usage < 85" | bc -l) )); then
        echo "$RISK_LOW"
    elif (( $(echo "$memory_usage >= 85 && $memory_usage < 95" | bc -l) )); then
        echo "$RISK_MEDIUM"
    else
        echo "$RISK_HIGH"
    fi
}

# 评估磁盘风险等级
evaluate_disk_risk() {
    local disk_usage=$1
    if (( $(echo "$disk_usage < 80" | bc -l) )); then
        echo "$RISK_NORMAL"
    else
        echo "$RISK_HIGH"
    fi
}

# 评估系统负载风险等级
evaluate_load_risk() {
    local load=$1
    if (( $(echo "$load < 70" | bc -l) )); then
        echo "$RISK_NORMAL"
    elif (( $(echo "$load >= 70 && $load < 85" | bc -l) )); then
        echo "$RISK_LOW"
    else
        echo "$RISK_MEDIUM"
    fi
}

# 评估日志风险等级
evaluate_log_risk() {
    local error_percent=$1
    if (( $(echo "$error_percent == 0" | bc -l) )); then
        echo "$RISK_NORMAL"
    elif (( $(echo "$error_percent > 0 && $error_percent < 5" | bc -l) )); then
        echo "$RISK_LOW"
    elif (( $(echo "$error_percent >= 5 && $error_percent < 10" | bc -l) )); then
        echo "$RISK_MEDIUM"
    else
        echo "$RISK_HIGH"
    fi
}

# 显示系统信息概览
show_system_info() {
    clear
    echo -e "${BLUE}==================== 系统信息概览 ====================${NC}"
    echo "主机名: $(hostname)"
    echo "操作系统: $(cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | sed 's/"//g')"
    echo "内核版本: $(uname -r)"
    echo "系统架构: $(uname -m)"
    echo "启动时间: $(uptime -s)"
    echo "运行时间: $(uptime -p)"
    echo "最后重启: $(last reboot | head -1 | awk '{print $5, $6, $7, $8}')"
    echo -e "${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 系统健康检查概览
show_health_overview() {
    clear
    echo -e "${BLUE}==================== 系统健康检查概览 ====================${NC}"
    
    # CPU 使用率检查
    echo -e "${YELLOW}----- CPU 状态 -----${NC}"
    cpu_usage=$(mpstat 1 1 | awk '/Average/ {printf "%.1f\n", 100 - $12}')
    cpu_risk=$(evaluate_cpu_risk $cpu_usage)
    echo "CPU 使用率: $cpu_usage%  [风险等级: $cpu_risk]"
    
    # 内存使用率检查
    echo -e "\n${YELLOW}----- 内存状态 -----${NC}"
    mem_total=$(free | awk '/Mem:/ {print $2}')
    mem_used=$(free | awk '/Mem:/ {print $3}')
    mem_usage=$(echo "scale=1; $mem_used / $mem_total * 100" | bc)
    mem_risk=$(evaluate_memory_risk $mem_usage)
    echo "内存使用率: $mem_usage%  [风险等级: $mem_risk]"
    
    # 磁盘使用率检查
    echo -e "\n${YELLOW}----- 磁盘状态 -----${NC}"
    disk_usage=$(df -P / | tail -1 | awk '{print $5}' | sed 's/%//')
    disk_risk=$(evaluate_disk_risk $disk_usage)
    echo "根分区使用率: $disk_usage%  [风险等级: $disk_risk]"
    
    # 系统负载检查
    echo -e "\n${YELLOW}----- 系统负载 -----${NC}"
    load_avg=$(uptime | awk -F'load average: ' '{print $2}' | cut -d',' -f1)
    cpu_count=$(grep -c ^processor /proc/cpuinfo)
    load_percent=$(echo "scale=1; $load_avg / $cpu_count * 100" | bc)
    load_risk=$(evaluate_load_risk $load_percent)
    echo "系统负载: $load_avg (相对负载: $load_percent%)  [风险等级: $load_risk]"
    
    # 系统日志检查
    echo -e "\n${YELLOW}----- 系统日志状态 -----${NC}"
    if [ -f "/var/log/syslog" ]; then
        log_file="/var/log/syslog"
    elif [ -f "/var/log/messages" ]; then
        log_file="/var/log/messages"
    else
        echo "未找到系统日志文件"
        log_file=""
    fi
    
    if [ -n "$log_file" ]; then
        total_lines=$(wc -l < "$log_file")
        error_lines=$(grep -c "ERROR" "$log_file")
        if [ $total_lines -gt 0 ]; then
            error_percent=$(echo "scale=2; $error_lines / $total_lines * 100" | bc)
            log_risk=$(evaluate_log_risk $error_percent)
            echo "日志错误比例: $error_percent% ($error_lines/$total_lines)  [风险等级: $log_risk]"
        else
            echo -e "${GREEN}日志文件为空，未发现错误${NC}"
        fi
    fi
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 监控系统资源使用情况
monitor_resources() {
    clear
    echo -e "${BLUE}==================== 系统资源监控 ====================${NC}"
    echo -e "${YELLOW}----- CPU 使用情况 -----${NC}"
    mpstat 1 2 | tail -5
    cpu_usage=$(mpstat 1 1 | awk '/Average/ {printf "%.1f\n", 100 - $12}')
    cpu_risk=$(evaluate_cpu_risk $cpu_usage)
    echo -e "CPU 使用率: $cpu_usage%  [风险等级: $cpu_risk]"
    
    echo -e "\n${YELLOW}----- 内存 使用情况 -----${NC}"
    free -h
    mem_total=$(free | awk '/Mem:/ {print $2}')
    mem_used=$(free | awk '/Mem:/ {print $3}')
    mem_usage=$(echo "scale=1; $mem_used / $mem_total * 100" | bc)
    mem_risk=$(evaluate_memory_risk $mem_usage)
    echo -e "内存使用率: $mem_usage%  [风险等级: $mem_risk]"
    
    echo -e "\n${YELLOW}-----  Swap 使用情况 -----${NC}"
    swapon --show
    
    echo -e "\n${YELLOW}----- 磁盘 I/O 情况 -----${NC}"
    iostat -x 1 2 | tail -10
    
    echo -e "\n${YELLOW}----- 网络 I/O 情况 -----${NC}"
    ifstat 1 2
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 检查磁盘空间
check_disk_space() {
    clear
    echo -e "${BLUE}==================== 磁盘空间检查 ====================${NC}"
    echo -e "${YELLOW}----- 磁盘分区使用情况及风险评估 -----${NC}"
    df -h | awk 'NR==1; NR>1 {print}' | while read -r line; do
        if echo "$line" | grep -q '/'; then
            usage=$(echo "$line" | awk '{print $5}' | sed 's/%//')
            risk=$(evaluate_disk_risk $usage)
            echo -e "$line  [风险等级: $risk]"
        else
            echo "$line"
        fi
    done
    
    echo -e "\n${YELLOW}----- 目录占用空间 Top 10 -----${NC}"
    du -h --max-depth=1 / 2>/dev/null | sort -hr | head -10
    
    echo -e "\n${YELLOW}----- 最近修改的大文件 (100MB以上) -----${NC}"
    find / -type f -size +100M -printf "%s %p\n" 2>/dev/null | sort -nr | head -10 | awk '{printf "%.2f GB\t%s\n", $1/(1024*1024*1024), $2}'
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 查看网络状态和连接
check_network() {
    clear
    echo -e "${BLUE}==================== 网络状态检查 ====================${NC}"
    echo -e "${YELLOW}----- IP 地址信息 -----${NC}"
    ip addr show | grep inet | grep -v '127.0.0.1' | grep -v '::1'
    
    echo -e "\n${YELLOW}----- 路由表 -----${NC}"
    ip route show
    
    echo -e "\n${YELLOW}----- DNS 配置 -----${NC}"
    cat /etc/resolv.conf | grep nameserver
    
    echo -e "\n${YELLOW}----- 活跃网络连接 -----${NC}"
    netstat -tuln
    
    echo -e "\n${YELLOW}----- 进程网络连接 -----${NC}"
    netstat -tulnp | head -20
    
    echo -e "\n${YELLOW}----- 防火墙规则 -----${NC}"
    if command -v ufw &> /dev/null; then
        ufw status
    elif command -v firewall-cmd &> /dev/null; then
        firewall-cmd --list-all
    else
        iptables -L | head -20
    fi
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 检查系统负载和进程
check_processes() {
    clear
    echo -e "${BLUE}==================== 系统负载和进程 ====================${NC}"
    echo -e "${YELLOW}----- 系统负载 -----${NC}"
    uptime
    load_avg=$(uptime | awk -F'load average: ' '{print $2}' | cut -d',' -f1)
    cpu_count=$(grep -c ^processor /proc/cpuinfo)
    load_percent=$(echo "scale=1; $load_avg / $cpu_count * 100" | bc)
    load_risk=$(evaluate_load_risk $load_percent)
    echo -e "系统相对负载: $load_percent%  [风险等级: $load_risk]"
    
    echo -e "\n${YELLOW}----- CPU 使用率最高的进程 -----${NC}"
    ps -eo %cpu,%mem,user,pid,cmd --sort=-%cpu | head -15
    
    echo -e "\n${YELLOW}----- 内存使用率最高的进程 -----${NC}"
    ps -eo %cpu,%mem,user,pid,cmd --sort=-%mem | head -15
    
    echo -e "\n${YELLOW}----- 僵尸进程 -----${NC}"
    zombie_count=$(ps -eo stat | grep -c '^Z')
    if [ $zombie_count -eq 0 ]; then
        echo -e "${GREEN}没有发现僵尸进程${NC}"
    else
        echo -e "${RED}发现 $zombie_count 个僵尸进程:${NC}"
        ps -eo stat,user,pid,cmd | grep '^Z'
    fi
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 服务状态检查
check_services() {
    clear
    echo -e "${BLUE}==================== 服务状态检查 ====================${NC}"
    
    # 检测系统使用的服务管理器
    if command -v systemctl &> /dev/null; then
        echo -e "${YELLOW}----- 系统服务状态 (systemd) -----${NC}"
        systemctl list-units --type=service --state=running | head -20
        
        echo -e "\n${YELLOW}----- 启动失败的服务 -----${NC}"
        failed_services=$(systemctl --failed --type=service | grep -v 'LOAD   = failed' | wc -l)
        if [ $failed_services -eq 0 ]; then
            echo -e "${GREEN}没有启动失败的服务${NC}"
        else
            echo -e "${RED}发现 $failed_services 个启动失败的服务:${NC}"
            systemctl --failed --type=service
        fi
    elif command -v service &> /dev/null; then
        echo -e "${YELLOW}----- 系统服务状态 (sysvinit) -----${NC}"
        service --status-all | head -20
    fi
    
    echo -e "\n${YELLOW}----- 输入服务名称查看详细状态 (如: sshd) -----${NC}"
    read -p "服务名称 (留空返回): " service_name
    
    if [ -n "$service_name" ]; then
        if command -v systemctl &> /dev/null; then
            systemctl status $service_name
        else
            service $service_name status
        fi
        echo ""
    fi
    
    echo -e "${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 系统日志分析（增强版）
analyze_logs() {
    clear
    echo -e "${BLUE}==================== 系统日志分析 ====================${NC}"
    echo -e "${YELLOW}1. 系统错误日志 (/var/log/error 或 /var/log/messages)${NC}"
    echo -e "${YELLOW}2. 认证日志 (/var/log/auth.log 或 /var/log/secure)${NC}"
    echo -e "${YELLOW}3. 内核日志 (/var/log/kern.log)${NC}"
    echo -e "${YELLOW}4. SSH 日志${NC}"
    echo -e "${YELLOW}5. Apache/Nginx 访问日志${NC}"
    echo -e "${YELLOW}6. 最近的系统消息 (dmesg)${NC}"
    echo -e "${YELLOW}7. 自定义日志文件分析${NC}"
    
    read -p "请选择要查看的日志类型 (1-7): " log_choice
    local log_file=""
    local error_percent=0
    local total_lines=0
    local error_lines=0
    
    case $log_choice in
        1)
            echo -e "\n${YELLOW}----- 系统错误日志分析 -----${NC}"
            if [ -f "/var/log/errors" ]; then
                log_file="/var/log/errors"
            elif [ -f "/var/log/messages" ]; then
                log_file="/var/log/messages"
            else
                echo -e "${RED}错误日志文件不存在${NC}"
                log_file=""
            fi
            ;;
        2)
            echo -e "\n${YELLOW}----- 认证日志分析 -----${NC}"
            if [ -f "/var/log/auth.log" ]; then
                log_file="/var/log/auth.log"
            elif [ -f "/var/log/secure" ]; then
                log_file="/var/log/secure"
            else
                echo -e "${RED}认证日志文件不存在${NC}"
                log_file=""
            fi
            ;;
        3)
            echo -e "\n${YELLOW}----- 内核日志分析 -----${NC}"
            if [ -f "/var/log/kern.log" ]; then
                log_file="/var/log/kern.log"
            else
                echo -e "${RED}内核日志文件不存在${NC}"
                log_file=""
            fi
            ;;
        4)
            echo -e "\n${YELLOW}----- SSH 日志分析 -----${NC}"
            if [ -f "/var/log/auth.log" ]; then
                log_file="/var/log/auth.log"
            elif [ -f "/var/log/secure" ]; then
                log_file="/var/log/secure"
            else
                echo -e "${RED}未找到SSH日志${NC}"
                log_file=""
            fi
            ;;
        5)
            echo -e "\n${YELLOW}----- Web服务器日志分析 -----${NC}"
            if [ -f "/var/log/apache2/access.log" ]; then
                log_file="/var/log/apache2/access.log"
            elif [ -f "/var/log/nginx/access.log" ]; then
                log_file="/var/log/nginx/access.log"
            else
                echo -e "${RED}未找到Web服务器日志${NC}"
                log_file=""
            fi
            ;;
        6)
            echo -e "\n${YELLOW}----- 系统消息分析 -----${NC}"
            dmesg | tail -n 50
            # 对于dmesg，我们直接显示内容而不进行百分比分析
            log_file=""
            ;;
        7)
            echo -e "\n${YELLOW}----- 自定义日志文件分析 -----${NC}"
            read -p "请输入日志文件路径: " custom_log
            if [ -f "$custom_log" ] && [ -r "$custom_log" ]; then
                log_file="$custom_log"
            else
                echo -e "${RED}指定的日志文件不存在或无法读取${NC}"
                log_file=""
            fi
            ;;
        *)
            echo -e "${RED}无效的选择${NC}"
            log_file=""
            ;;
    esac
    
    # 如果日志文件存在，进行错误分析
    if [ -n "$log_file" ] && [ -f "$log_file" ]; then
        total_lines=$(wc -l < "$log_file")
        error_lines=$(grep -ci "ERROR" "$log_file")
        
        if [ $total_lines -gt 0 ]; then
            error_percent=$(echo "scale=2; $error_lines / $total_lines * 100" | bc)
            log_risk=$(evaluate_log_risk $error_percent)
            echo -e "\n${YELLOW}----- 日志错误统计 -----${NC}"
            echo -e "总记录数: $total_lines"
            echo -e "错误记录数: $error_lines"
            echo -e "错误比例: $error_percent%  [风险等级: $log_risk]"
        fi
        
        echo -e "\n${YELLOW}----- 最近的错误记录 -----${NC}"
        if [ $log_choice -eq 4 ]; then
            # 对于SSH日志，我们只过滤sshd相关内容
            grep "sshd" "$log_file" | grep -i "error" | tail -n 20
        else
            grep -i "error" "$log_file" | tail -n 20
        fi
        
        echo -e "\n${YELLOW}----- 最近的日志记录 -----${NC}"
        tail -n 20 "$log_file"
    fi
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 简单的安全检查
security_check() {
    clear
    echo -e "${BLUE}==================== 安全检查 ====================${NC}"
    
    echo -e "${YELLOW}----- 密码策略检查 -----${NC}"
    if [ -f "/etc/login.defs" ]; then
        grep -E 'PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_WARN_AGE' /etc/login.defs
    fi
    
    echo -e "\n${YELLOW}----- 禁止root SSH登录检查 -----${NC}"
    if [ -f "/etc/ssh/sshd_config" ]; then
        grep "PermitRootLogin" /etc/ssh/sshd_config
    fi
    
    echo -e "\n${YELLOW}----- 有sudo权限的用户 -----${NC}"
    grep -Po '^sudo.+:\K.*$' /etc/group
    
    echo -e "\n${YELLOW}----- 最近的登录失败 -----${NC}"
    lastb | head -10
    
    echo -e "\n${YELLOW}----- SUID/SGID 文件检查 -----${NC}"
    find / -perm /6000 -type f 2>/dev/null | head -10
    
    echo -e "\n${YELLOW}----- 开放端口检查 -----${NC}"
    netstat -tuln | grep -v '127.0.0.1'
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 系统备份功能
system_backup() {
    clear
    echo -e "${BLUE}==================== 系统备份 ====================${NC}"
    echo -e "${YELLOW}注意: 此功能将创建重要系统文件和配置的备份${NC}"
    
    read -p "请输入备份存储路径 (默认: /backup): " backup_path
    backup_path=${backup_path:-/backup}
    
    # 创建备份目录
    if [ ! -d "$backup_path" ]; then
        mkdir -p "$backup_path"
        if [ $? -ne 0 ]; then
            echo -e "${RED}无法创建备份目录 $backup_path${NC}"
            read -p "按回车键返回主菜单..."
            return
        fi
    fi
    
    # 生成备份文件名
    backup_file="$backup_path/system-backup-$(date +%Y%m%d-%H%M%S).tar.gz"
    
    echo -e "\n${YELLOW}开始备份系统配置...${NC}"
    
    # 备份重要文件和目录
    tar -czf "$backup_file" \
        /etc \
        /var/spool/cron \
        /home \
        --exclude=/home/*/.cache \
        --exclude=/home/*/.local/share/Trash \
        2>/dev/null
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}备份成功! 备份文件: $backup_file${NC}"
        echo -e "文件大小: $(du -h "$backup_file" | awk '{print $1}')"
    else
        echo -e "${RED}备份失败!${NC}"
        if [ -f "$backup_file" ]; then
            rm "$backup_file"
        fi
    fi
    
    echo -e "\n${YELLOW}最近的备份:${NC}"
    ls -lht "$backup_path"/*.tar.gz 2>/dev/null | head -5
    
    echo -e "\n${BLUE}=====================================================${NC}"
    read -p "按回车键返回主菜单..."
}

# 显示主菜单
show_menu() {
    clear
    echo -e "${BLUE}=====================================================${NC}"
    echo -e "${GREEN}              Linux 运维多功能工具箱 v2.0           ${NC}"
    echo -e "${BLUE}=====================================================${NC}"
    echo -e "${YELLOW}1. 系统信息概览${NC}"
    echo -e "${YELLOW}2. 系统健康检查概览 (带风险评估)${NC}"
    echo -e "${YELLOW}3. 系统资源监控 (CPU/内存/磁盘I/O/网络)${NC}"
    echo -e "${YELLOW}4. 磁盘空间检查${NC}"
    echo -e "${YELLOW}5. 网络状态和连接检查${NC}"
    echo -e "${YELLOW}6. 系统负载和进程检查${NC}"
    echo -e "${YELLOW}7. 服务状态检查与管理${NC}"
    echo -e "${YELLOW}8. 系统日志分析 (带错误比例统计)${NC}"
    echo -e "${YELLOW}9. 安全检查${NC}"
    echo -e "${YELLOW}10. 系统备份${NC}"
    echo -e "${RED}0. 退出工具${NC}"
    echo -e "${BLUE}=====================================================${NC}"
}

# 主程序
main() {
    check_root
    
    # 检查必要的工具是否安装
    check_dependencies() {
        local dependencies=("mpstat" "free" "swapon" "iostat" "ifstat" "netstat" "bc")
        for dep in "${dependencies[@]}"; do
            if ! command -v "$dep" &> /dev/null; then
                echo -e "${YELLOW}缺少必要工具 $dep，正在尝试安装...${NC}"
                if command -v apt &> /dev/null; then
                    apt update && apt install -y sysstat net-tools bc
                    break
                elif command -v yum &> /dev/null; then
                    yum install -y sysstat net-tools bc
                    break
                else
                    echo -e "${RED}无法自动安装依赖，请手动安装 $dep${NC}"
                    exit 1
                fi
            fi
        done
    }
    
    check_dependencies
    
    while true; do
        show_menu
        read -p "请选择功能 (0-10): " choice
        
        case $choice in
            1) show_system_info ;;
            2) show_health_overview ;;
            3) monitor_resources ;;
            4) check_disk_space ;;
            5) check_network ;;
            6) check_processes ;;
            7) check_services ;;
            8) analyze_logs ;;
            9) security_check ;;
            10) system_backup ;;
            0) 
                echo -e "${GREEN}感谢使用Linux运维工具箱，再见！${NC}"
                exit 0 
                ;;
            *) 
                echo -e "${RED}无效的选择，请重试。${NC}"
                read -p "按回车键继续..."
                ;;
        esac
    done
}

# 启动主程序
main
